﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Text;
using System.Configuration;
using System.Drawing;

using ESOL.Common;
using System.Data;
using System.Reflection;

namespace ESOL.WebServices
{
    /// <summary>
    /// EsolService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class EsolService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod(Description = "Web   服务提供的方法，返回是否文件上载成功与否。 ")]
        public string UploadFile(byte[] fs, string FileName)
        {
            try
            {
                ///定义并实例化一个内存流，以存放提交上来的字节数组。 
                MemoryStream m = new MemoryStream(fs);
                ///定义实际文件对象，保存上载的文件。
                FileStream f = new FileStream(GetFileStream(FileName) + @"\" + FileName, FileMode.Create);
                //FileStream f = new FileStream(@"f:\" + FileName, FileMode.Create);
                // FileStream f = new FileStream(Server.MapPath(". ") + "\\ " + FileName, FileMode.Create);
                ///把内存里的数据写入物理文件 
                m.WriteTo(f);
                m.Close();
                f.Close();
                f = null;
                m = null;
                return "图片已经上传成功。 ";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        [WebMethod(Description = "Web   服务提供的方法，返回二进制文件字节数组。 ")]
        public byte[] DownloadFile(string FileName)
        {
            try
            {
                byte[] b = FileToByte(GetFileStream(FileName) + @"\" + FileName);
                return b;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        [WebMethod(Description = "Web   服务提供的方法，返回二进制文件字节数组。 ")]
        public DataSet DownloadFiles(DataSet DsFileNames)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("PRODUCT_CODE");
            dt.Columns.Add("BLUEPRINT_BYTE", typeof(byte[]));
            DataColumn[] keys = new DataColumn[1];
            keys[0] = dt.Columns[0];
            dt.PrimaryKey = keys;
            foreach (DataRow m in DsFileNames.Tables[0].Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows.Find(m["PRODUCT_CODE"].ToString()) != null)
                        continue;
                }

                byte[] b = null;
                try
                {
                    b = FileToByte(GetFileStream(m["PRODUCT_CODE"].ToString()) + "\\" + m["PRODUCT_CODE"].ToString()+".jpg");
                }
                catch (Exception ex)
                {
                }
                DataRow dr = dt.NewRow();
                dr[0] = m["PRODUCT_CODE"].ToString();
                dr[1] = b;
                dt.Rows.Add(dr);
            }
            ds.Tables.Add(dt.Copy());
            return ds;
        }
        public DataSet DownLoadFiles(DataSet DsFileNames,string FilePath,out string errMsg)
        {
            errMsg = "";
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("FileName");
            dt.Columns.Add("FileData", typeof(byte[]));
            DataColumn[] keys = new DataColumn[1];
            keys[0] = dt.Columns[0];
            dt.PrimaryKey = keys;
            foreach (DataRow drFileName in DsFileNames.Tables[0].Rows)
            {
                string sFileName = drFileName["FileName"].ToString();
                string sFileFullName = FilePath + sFileName;
                byte[] b = null;
                try
                {
                    b = FileToByte(sFileFullName);
                }                    
                catch (Exception ex)
                {
                    errMsg = ex.Message;
                }
                DataRow dr=dt.NewRow();
                dr["FileName"] = sFileName;
                dr["FileData"] = b;
                dt.Rows.Add(dr);
            }
            ds.Tables.Add(dt);
            return ds;
        }
        private string GetFileStream(string FileName)
        {
            string sOut = "";
            string DeflePictureFile = ConfigurationManager.AppSettings["PictureFileStrength"];
            string sClass1 = "";
            string sClass2 = "";
            string sType = "";
            sClass1 = FileName.Substring(0, 1);
            sClass2 = FileName.Substring(1, 3);
            sType = FileName.Substring(4, 5);
            sOut = DeflePictureFile + @"\" + sClass1 + @"\" + sClass2 + @"\" + sType;
            if (!Directory.Exists(sOut))//如果不存在文件夹
            {
                Directory.CreateDirectory(sOut);//创建文件夹
            }

            return sOut;
        }
        private static byte[] FileToByte(string pStrFName)
        {
            FileInfo fi = new FileInfo(pStrFName);
            FileStream fs = fi.OpenRead();
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return bytes;
        }

        #region Hr
        [WebMethod(Description = "获取上传的员工照片的路径")]
        public string GetEmployeePhotoPath()
        {
            return WebCommonFunctions.EmployeePhotoPath();
        }
        [WebMethod(Description = "获取上传的附件的路径")]
        public string GetEmployeefilePath()
        {
            return WebCommonFunctions.EmployeefilePath();
        }
        [WebMethod(Description = "获取上传的离职附件的路径")]
        public string GetPersonLeave()
        {
            return WebCommonFunctions.PersonLeave();
        }
        [WebMethod(Description = "Web   服务提供的方法，返回是否文件上载成功与否。 ")]
        public bool UploadFileNew(byte[] fs, string FileName, out string errMsg)
        {
            errMsg = "";
            try
            {
                ///定义并实例化一个内存流，以存放提交上来的字节数组。 
                MemoryStream m = new MemoryStream(fs);
                ///定义实际文件对象，保存上载的文件。
                FileStream f = new FileStream(FileName, FileMode.Create);
                m.WriteTo(f);
                m.Close();
                f.Close();
                f = null;
                m = null;
                return true;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return false;
            }
        }
        [WebMethod(Description = "Web   服务提供的方法，返回是否文件集合上载成功与否。 ")]
        public bool UploadFiles(DataSet ds, string path, out string errMsg)
        {
            errMsg = "";
            if (ds != null && ds.Tables[0] != null)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    try
                    {
                        byte[] fs = (byte[])ds.Tables[0].Rows[i][0];
                        string filename = path + "\\" + ds.Tables[0].Rows[i][1].ToString();
                        ///定义并实例化一个内存流，以存放提交上来的字节数组。 
                        MemoryStream m = new MemoryStream(fs);
                        ///定义实际文件对象，保存上载的文件。
                        FileStream f = new FileStream(filename, FileMode.Create);
                        m.WriteTo(f);
                        m.Close();
                        f.Close();
                        f = null;
                        m = null;
                    }
                    catch (Exception ex)
                    {
                        errMsg += ds.Tables[0].Rows[i][1] + "保存失败！\r";
                        continue;
                    }
                }
                return true;
            }
            else return false;
        }

        [WebMethod(Description = "Web   服务提供的方法，返回二进制文件字节数组。 ")]
        public byte[] DownloadFileNew(string FileName, out string errMsg)
        {
            errMsg = "";
            try
            {
                byte[] b = FileToByte(FileName);
                return b;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                return null;
            }
        }
        #endregion

        #region MST
        [WebMethod(Description = "获取上传的供应商附件的路径")]
        public string SupplierAttachedPath(string supplierCode)
        {
            return WebCommonFunctions.SupplierAttachedPath(supplierCode);
        }

        [WebMethod(Description = "获取上传的签名图片的路径")]
        public string SignaturePicPath()
        {
            return WebCommonFunctions.SignaturePicPath();
        }
        #endregion

        #region Pur
        [WebMethod(Description = "获取上传的采购订单附件的路径")]
        public string PurchaseOrderAttachedPath()
        {
            return WebCommonFunctions.PurchaseOrderAttachedPath();
        }
        [WebMethod(Description = "获取上传的采购询价单附件的路径")]
        public string PurchaseQuoteAttachedPath()
        {
            return WebCommonFunctions.PurchaseQuoteAttachedPath();
        }
        #endregion

        #region Update
        [WebMethod(Description = "获取自动更新程序的目录")]
        public string GetUpdateFolderName()
        {
            string path = HttpRuntime.AppDomainAppPath + WebCommonFunctions.UpdateFileFolder();
            if (Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);
            }
            return WebCommonFunctions.UpdateFileFolder();
        }
        [WebMethod(Description = "获取当前版本的版本号")]
        public string GetLatestVersion()
        {
            try
            {
                string path = HttpRuntime.AppDomainAppPath + WebCommonFunctions.UpdateFileFolder();
                if (Directory.Exists(path) == false)
                {
                    Directory.CreateDirectory(path);
                }
                MemoryStream memStream;
                using (FileStream stream = new FileStream(path + "\\" + "ESOL.WinUI.exe", FileMode.Open))
                {
                    using (memStream = new MemoryStream())
                    {
                        int res;
                        byte[] b = new byte[4096];
                        while ((res = stream.Read(b, 0, b.Length)) > 0)
                        {
                            memStream.Write(b, 0, b.Length);
                        }
                    }
                }
                Assembly assDll = Assembly.Load(memStream.ToArray());
                string version = assDll.GetName().Version.ToString();
                if (memStream != null)
                {
                    memStream.Dispose();
                }
                return version;
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
        }
        [WebMethod(Description = "获取要更新的所有文件名")]
        public string[] GetUpdateFiles()
        {
            string path = HttpRuntime.AppDomainAppPath + WebCommonFunctions.UpdateFileFolder();
            if (Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);
            }
            return Directory.GetFiles(path);
        }
        #endregion

        #region Sales
        [WebMethod(Description = "获取上传的销售订单附件的路径")]
        public string SalesOrderAttachedPath()
        {
            return WebCommonFunctions.SalesOrderAttachedPath();
        }
        [WebMethod(Description = "获取上传的销售询价单附件的路径")]
        public string SalesQuoteAttachedPath()
        {
            return WebCommonFunctions.SalesQuoteAttachedPath();
        }
        #endregion

        #region Rep
        [WebMethod(Description = "获取上传的财产登记单附件的路径")]
        public string ProductRegisterAttachedPath()
        {
            return WebCommonFunctions.ProductRegisterAttachedPath();
        }

        [WebMethod(Description = "获取上传的维修报告附件路径")]
        public string RepairReportAttachedPath()
        {
            return WebCommonFunctions.RepairReportAttachedPath();
        }

        [WebMethod(Description = "上传维修报告,返回成功的文件名")]
        public bool UploadRepairReportAttachedFiles(DataSet ds, string path, out string msgFiles)
        {
            msgFiles = "";
            if (ds != null && ds.Tables[0] != null)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    try
                    {
                        byte[] fs = (byte[])ds.Tables[0].Rows[i][0];
                        string filename = path + "\\" + ds.Tables[0].Rows[i][1].ToString();
                        ///定义并实例化一个内存流，以存放提交上来的字节数组。 
                        MemoryStream m = new MemoryStream(fs);
                        ///定义实际文件对象，保存上载的文件。
                        FileStream f = new FileStream(filename, FileMode.Create);
                        m.WriteTo(f);
                        m.Close();
                        f.Close();
                        f = null;
                        m = null;
                        msgFiles += ds.Tables[0].Rows[i][1].ToString() + ";";
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                }
                return true;
            }
            else return false;
        }

        #endregion

        #region Blueprint
        public bool GetBptApplicationApproveFlag()
        {
            string flag = ConfigurationManager.AppSettings["BptApplicationApproveFlag"];
            if (flag.Equals("Y"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        [WebMethod(Description = "获取上传图纸的路径")]
        public string BlueprintPath(string  sCodeName)
        {
            string sBasePath = WebCommonFunctions.PictureFilePath();
            string sClass1 = "";
            string sClass2 = "";
            string sType = "";
            sClass1 = sCodeName.Substring(0, 1);
            sClass2 = sCodeName.Substring(1, 3);
            sType = sCodeName.Substring(4, 5);
            string sFilePath = sBasePath + @"\" + sClass1 + @"\" + sClass2 + @"\" + sType;
            return sFilePath;
        }

        [WebMethod(Description = "上传制图任务附件")]
        public bool UpLodeBptappfiles(byte[] fs, string FileName)
        {
            try
            {
                ///定义并实例化一个内存流，以存放提交上来的字节数组。 
                MemoryStream m = new MemoryStream(fs);
                ///定义实际文件对象，保存上载的文件。
                string path = WebCommonFunctions.BptAttachedPath();//ConfigurationManager.AppSettings["BptAppAttachedPath"];
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                FileStream f = new FileStream(path + @"\" + FileName, FileMode.Create);
                ///把内存里的数据写入物理文件 
                m.WriteTo(f);
                m.Close();
                f.Close();
                f = null;
                m = null;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        [WebMethod(Description = "下载制图任务附件")]
        public byte[] DownLodeBptappfiles(string FileName)
        {
            try
            {
                string path = ConfigurationManager.AppSettings["BptAppAttachedPath"];
                byte[] b = FileToByte(path + @"\" + FileName);
                return b;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion
    }
}